package userserv

import (
	"codedef"
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"strings"
)

func onLoadFarm(w http.ResponseWriter, r *http.Request) {
	account := r.Header.Get("account")
	farmId := r.URL.Query().Get("fid")

	conn := rhelper.Pool().Get()
	defer conn.Close()

	fields, err := redis.Strings(conn.Do("HMGET", rhelper.FarmHash+farmId, "name", "tasks", "plan", "account", "description"))
	if err != nil {
		log.Println(err)
		replyError(w, codedef.ERR_DATABASE)
		return
	}

	accountString := fields[3]
	if strings.Contains(accountString, account) == false {
		log.Println("Account not in farm's account list, can't access farm")
		replyError(w, codedef.ERR_FARM_NOT_BELONG2_ACCOUNT)
		return
	}

	type task_s struct {
		Id   string `json:"id,omitempty"`
		Name string `json:"name,omitempty"`
	}

	type plan_s struct {
		Id   string `json:"id,omitempty"`
		Name string `json:"name,omitempty"`
	}

	type farm_s struct {
		Id          string   `json:"id,omitempty"`
		Name        string   `json:"name,omitempty"`
		Description string   `json:"description,omiempty"`
		Tasks       []task_s `json:"tasks"`
		Plans       []plan_s `json:"plans"`
	}

	farm := farm_s{}

	farm.Name = fields[0]
	farm.Id = farmId
	farm.Description = fields[4]

	taskStringArray := commaString2Array(fields[1])
	planStringArray := commaString2Array(fields[2])

	if len(taskStringArray) > 0 {
		tasks := make([]task_s, len(taskStringArray))
		var index int = 0
		for _, taskString := range taskStringArray {
			if taskString == "" {
				continue
			}

			fields, err = redis.Strings(conn.Do("HMGET", rhelper.TaskHash+taskString, "name", "status"))
			if err != nil {
				log.Println(err)
				continue
			}

			task := task_s{}
			task.Id = taskString
			task.Name = fields[0]
			tasks[index] = task
			index++
		}

		tasks = tasks[0:index]
		farm.Tasks = tasks
	}

	if len(planStringArray) > 0 {
		plans := make([]plan_s, len(planStringArray))
		var index int = 0
		for _, planString := range planStringArray {
			if planString == "" {
				continue
			}

			fields, err = redis.Strings(conn.Do("HMGET", rhelper.PlanHash+planString, "name", "status"))
			if err != nil {
				log.Println(err)
				continue
			}

			plan := plan_s{}
			plan.Id = planString
			plan.Name = fields[0]
			plans[index] = plan
			index++
		}

		plans = plans[0:index]
		farm.Plans = plans
	}

	buf, err := json.Marshal(farm)
	if err != nil {
		log.Println(err)
		replyError(w, codedef.ERR_ENCODE)
		return
	}

	w.Write(buf)
}

func init() {
	myMux.muxHandlers.HandleFunc("/loadFarm", onLoadFarm)
}
